<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/31
 * Time: 21:37
 */

namespace app\api\validate;

use app\lib\exception\ParamersException;

class Order extends BaseValidate
{
    //定义一个验证二维数组的验证规则
    protected $rule = [
        'products' => 'checkProducts',
    ];
    //定义一个验证每一个元素的统一的规则
    protected $singleRule = [
        'id' => 'require|isPositiveInteger',
        'count' => 'require|isPositiveInteger',
    ];
    //自定义的方法
    protected function checkProducts($value)
    {
        //为空则异常
        if(empty($value)) throw new ParameterException(['msg' => '参数不能为空!']);
        //不为数组则参数格式异常
        if(!is_array($value)) throw new ParamersException(['msg' => '参数格式不正确!']);
        ///编历之后再验证
        foreach ($value as $product) {
            $this -> checkProduct($product);
        }
    }
    //把BaseValidate实例化,传入参数,再实例一个validate的对象,参入$rule的规则.重点是一个类可以被实例化多次
    protected function checkProduct($value)
    {
        $validate = new BaseValidate($this -> singleRule);
        $result = $validate -> check($value);
        if(!$result) throw new ParamersException(['msg' => $validate -> getError()]);
    }
}